梦入琼楼寒有月,行过石树冻无烟

Vue 自定义事件

事件在vue中主要被定义为当你点击他的时候,他会作出什么反映,这就比如我们前几章所介绍的当按下鼠标时,则值每次分别增加1,则这种被称之为“事件”。

事件命名

Vue的事件命名不同于 prop,即事件名不存在任何的自动化大小写转换,即触发、监听的事件必须完全匹配这个事件所用的名称,如:

1
this.$emit('eventName')

事件定义


在Vue 中我们可以通过使用v-on指令或者@来简写作为 DOM 元素的事件绑定,而除此之外我们还可以使用 Vue 事件接口(Eventd interface)中的

  1. $on (eventName)
  2. $emit(eventName)

通过上述 Vue 接口事件,可分别使用$on来进行监听事件以及将$emit用于触发事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<div id="app">
<div id="event-example">
<button-event v-on:event="eventGo"></button-event>
<button-event v-on:event="eventGo"></button-event>
</div>
</div>
<script>
Vue.component('button-event', {
template: '<button v-on:click="increaseUp">{{ echo }}</button>',
data: function() {
return {
echo: 0
}
},
methods: {
increaseUp: function() {
this.echo +=1
this.$emit('event')
}
},
})
new Vue({
el: '#event-example',
data: {
total: 0
},
methods: {
eventGo: function() {
this.total += 1
}
}
})
</script>

v-model 自定义组件

表单


Vue 中v-model指令可以用于在表单或组件上自动创建一个双向的绑定,就为明显的例子无非就是获取表单输入,通过表单输入以及获取表单输入即可是一个双向绑定,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div id="app">
<model-input v-model="number"></model-input>
<p>{{number}}</p>
</div>
<script>
Vue.component('model-input', {
template: `
<input ref="input" :value="value" @input="$emit('input',$event.target.value)">
`,
props: ['value'],
})
new Vue({
el: '#app',
data: {
number: null,
}
})
</script>

多选


在上述的流程图中,我们合租要通过使用v-on以及v-show来分别判断鼠标事件以及真假值的判断,当check被点击的时候,则默认将v-show改变为 true状态使得其变得可见,默认为false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<div id="app">
<show-checkbox v-model="check"></show-checkbox>
<div v-show="check">
以同意相关注册协议
</div>
</div>
<script>
Vue.component('show-checkbox', {
model: {
prop: 'checked',
event: 'change'
},
props: {
checked: Boolean
},
template: `
<input type="checkbox"
v-bind:checked="checked"
v-on:change="$emit('change', $event.target.checked)"
>
`
})
new Vue({
el: '#app',
data: {
check: false
}
})
</script>
⬅️ Go back